
#import "AppController.h"

@implementation AppController

- appDidInit:sender
{
    EODatabaseChannel *channel = [(id)[controller dataSource] databaseChannel];
    [channel setDelegate:self];

    // Set a controller in memory sort by department and then lastName
    [controller setSortOrdering:[NSArray arrayWithObjects:
        [EOKeySortOrdering keyOrderingWithKey:@"departmentName" ordering:NSOrderedAscending],
        [EOKeySortOrdering keyOrderingWithKey:@"lastName" ordering:NSOrderedAscending], nil]];
        
    [controller fetch];
    return self;
}

- validatesOnChange:sender
{
    [self setValidatesImmediately:[sender intValue]];
    return self;
}

- saveChanges:sender
{
    // we can't call saveToDataSource directly since it doesn't automatically
    // call saveToObjects first (bummer!)
    if ([controller saveToObjects] && [controller saveToDataSource])
        return self;
    return nil;
}


- (NSDictionary *)databaseChannel:channel
    willRefetchObject:object
    fromSnapshot:(NSDictionary *)snapshot
{
    // Our object is being refetched, and will be refreshed with the given
    // snapshot.  Snapshot is really the set of class properties that would be
    // passed to us in takeValuesFromDictionary (not the one we'd get from
    // snapshotForObject).
    // PROBLEM: if we have uncommitted edits to this object, they could get
    // reset by refetching.
    // OPTIONS:
    // 1) Diff our object against it current (old) snapshot and see if we've
    //    made any changes.  Only allow the update it we have.  Might be slow.
    // 2) If our EO keeps an explicit lock flag, we could check if it's locked
    //    for update.  Sadly, we have no such lock.
    // 3) Always ignore the refetch.  Disadvantage: we'll never be able to
    //    refresh to see new changes made by others in the server.
    // Since efficiency is not a major issue in this example, we'll choose #1.
    NSDictionary *originalSnapshot = [[channel databaseContext] snapshotForObject:object];
    NSDictionary *currentSnapshot = [object valuesForKeys:[originalSnapshot allKeys]];
    if (![originalSnapshot isEqual:currentSnapshot]) {
        // Conflicting update
        // NSLog(@"Attempt to refetch a modified object with current snapshot: %@", currentSnapshot);
        return nil;
    }
    // Okay, no conflict, so allow the update
    return snapshot;
}

@end
